package com.ruoyi.web.controller.modules;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.DownloadImage;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.modules.domain.Credit;
import com.ruoyi.modules.service.CreditService;
import com.ruoyi.web.controller.ocr.utils.AuthService;
import com.ruoyi.web.controller.ocr.utils.Base64Util;
import com.ruoyi.web.controller.ocr.utils.FileUtil;
import com.ruoyi.web.controller.ocr.utils.HttpUtil;
import io.swagger.annotations.ApiOperation;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * 学生身份证照片上传
 */
@RestController
@RequestMapping("/student/upload")
public class uploadController {

    // iocr识别apiUrl
    private static String recogniseUrl = "https://aip.baidubce.com/rest/2.0/solution/v1/iocr/recognise";

    @Autowired
    private CreditService creditService;

   // private static String accessToken = "24.da476e7d38dcb093a1e1d9cae599b77a.2592000.1607996896.282335-22662812";

    private String getAccessToken() {
        return AuthService.getAuth("Sq0oIxYdOm766hxxMKkl8Lv4", "DIVGksjwFGMd60lbUTFT6rlRx5hgN4Gx");
    }

    /**
     * 上传身份证照片正面
     *
     * @param file 文件
     * @param creditId 贷款编号
     * @return
     * @throws Exception
     */
    @ApiOperation("上传身份证照片正面")
    @Log(title = "上传身份证照片正面", businessType = BusinessType.UPDATE)
    @PostMapping("/front")
    public AjaxResult updateCreditIdentityFileOfFront(@RequestParam("identityfileoffront") MultipartFile file, @RequestParam("creditId") Long creditId, @RequestParam("userName") String userName) throws Exception {
        if (creditId != 0) {
            AjaxResult ajax = AjaxResult.success();
            Credit credit = creditService.selectCreditById(creditId);
            String identityPathOfFront = FileUploadUtils.upload(RuoYiConfig.getIdentityPathOfFront(), file);
            creditService.updateCreditIdentityFileOfFront(creditId, identityPathOfFront);

            DownloadImage downloadImage = new DownloadImage();
            // 是能够下载的，可以下载的前提是可以在服务器上访问，因为前端上传之后，后端已经进行updateCreditIdentityFileOfFront方法保存到数据库
            String httpUrlStr = "http://localhost:8080" + identityPathOfFront;
            String fileName = "即将识别的图片.jpg";

            // 将服务器上图片下载到本地
            downloadImage.download(httpUrlStr, fileName);

            byte[] imgData = FileUtil.readFileByBytes("E:/images/" + fileName);
            String imgStr = Base64Util.encode(imgData);
            // 请求模板参数
            String recogniseParams = "templateSign=id_card_front&image=" + URLEncoder.encode(imgStr, "UTF-8");

            // 手动每次获取 accessToken, 避免过期
            String accessToken = getAccessToken();

            // 请求模板识别
            String result = HttpUtil.post(recogniseUrl, accessToken, recogniseParams);

            System.out.println(result);

            // 将String转为org.json.JSONObject
            /**
             * result:{"data":{"ret":[{"word_name":"姓名","word":"谭卢钢"},{"word_name":"民族","word":"毛南"},{"word_name":"住址","word":"广西环江毛南族自治县下南乡才门村石望屯7号"},{"word_name":"公民身份号码","word":"452724199807151615"},{"word_name":"出生","word":"19980715"},{"word_name":"性别","word":"男"}],"templateSign":"id_card_front","templateName":"大陆身份证正面","scores":1.0,"isStructured":true,"logId":"160723112104534","version":1},"error_code":0,"error_msg":"","log_id":"160723112104534"}
             */
            // 得到json对象
            JSONObject jsonObject = new JSONObject(result);
            JSONObject data = jsonObject.getJSONObject("data");
            System.out.println(data);
            // 得到json数组
            JSONArray ret = data.getJSONArray("ret");
            System.out.println(ret);

            // 从数组中拿到一个JSONObject对象
            JSONObject retJSONObject1 = ret.getJSONObject(1);
            JSONObject retJSONObject3 = ret.getJSONObject(3);

            // 拿到对象中的一个字段
            String nation = retJSONObject1.getString("word"); // 民族
            String word = retJSONObject3.getString("word"); // 身份证号

            // 将该对象对应的值返回
            ajax.put("nation", nation);
            ajax.put("word", word);

            // 返回上传图片的地址
            ajax.put("identityOfFrontUrl", identityPathOfFront);

            // 更新
            credit.setIdentityPathOfFront(identityPathOfFront);
            credit.setUpdateTime(new Date());
            creditService.updateCredit(credit);
            return ajax;
        } else {
            AjaxResult ajax = AjaxResult.success();
            System.out.println("添加的时候creditId应该为0: 此时为" + creditId);
            String identityPathOfFront = FileUploadUtils.upload(RuoYiConfig.getIdentityPathOfFront(), file);
                // 添加
                Credit credit = new Credit();
                credit.setUserName(userName);
                credit.setIdentityPathOfFront(identityPathOfFront);
                creditService.insertCredit(credit);
                // 查询最新添加的记录
                Credit creditVo = creditService.selectNewCreateByUserName(userName);
                System.out.println("保存了一条记录，该记录现在只有主键id和identityPathOfFront两个字段");
                System.out.println(creditVo);
                creditService.updateCredit(creditVo);
                DownloadImage downloadImage = new DownloadImage();
                // 是能够下载的，可以下载的前提是可以在服务器上访问，因为前端上传之后，后端已经进行updateCreditIdentityFileOfFront方法保存到数据库
                String httpUrlStr = "http://localhost:8080" + identityPathOfFront;
                String fileName = "即将识别的图片.jpg";

                // 将服务器上图片下载到本地
                downloadImage.download(httpUrlStr, fileName);

                byte[] imgData = FileUtil.readFileByBytes("E:/images/" + fileName);
                String imgStr = Base64Util.encode(imgData);
                // 请求模板参数
                String recogniseParams = "templateSign=id_card_front&image=" + URLEncoder.encode(imgStr, "UTF-8");

                // 手动每次获取 accessToken, 避免过期
                String accessToken = getAccessToken();

                // 请求模板识别
                String result = HttpUtil.post(recogniseUrl, accessToken, recogniseParams);

                System.out.println(result);

                // 将String转为org.json.JSONObject
                /**
                 * result:{"data":{"ret":[{"word_name":"姓名","word":"谭卢钢"},{"word_name":"民族","word":"毛南"},{"word_name":"住址","word":"广西环江毛南族自治县下南乡才门村石望屯7号"},{"word_name":"公民身份号码","word":"452724199807151615"},{"word_name":"出生","word":"19980715"},{"word_name":"性别","word":"男"}],"templateSign":"id_card_front","templateName":"大陆身份证正面","scores":1.0,"isStructured":true,"logId":"160723112104534","version":1},"error_code":0,"error_msg":"","log_id":"160723112104534"}
                 */
                // 得到json对象
                JSONObject jsonObject = new JSONObject(result);
                JSONObject data = jsonObject.getJSONObject("data");
                System.out.println(data);
                // 得到json数组
                JSONArray ret = data.getJSONArray("ret");
                System.out.println(ret);

                // 从数组中拿到一个JSONObject对象
                JSONObject retJSONObject1 = ret.getJSONObject(1);
                JSONObject retJSONObject3 = ret.getJSONObject(3);

                // 拿到对象中的一个字段
                String nation = retJSONObject1.getString("word"); // 民族
                String word = retJSONObject3.getString("word"); // 身份证号

                // 将该对象对应的值返回
                ajax.put("nation", nation);
                ajax.put("word", word);

                ajax.put("identityOfFrontUrl", identityPathOfFront);

            return ajax;
        }
    }


    /**
     * 上传身份证照片反面
     * @param file 文件
     * @param creditId 贷款编号
     * @return
     * @throws IOException
     */
    @ApiOperation("上传身份证照片反面")
    @Log(title = "上传身份证照片反面", businessType = BusinessType.UPDATE)
    @PostMapping("/reverse")
    public AjaxResult updateCreditIdentityFileOfReverse(@RequestParam("identityfileofreverse") MultipartFile file, @RequestParam("creditId") Long creditId, @RequestParam("userName") String userName) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        if (creditId != 0) {
            Credit credit = creditService.selectCreditById(creditId);
            String identityPathOfReverse = FileUploadUtils.upload(RuoYiConfig.getIdentityPathOfReverse(), file);
            if (creditService.updateCreditIdentityFileOfReverse(creditId, identityPathOfReverse))
            {
                ajax.put("identityOfReverseUrl", identityPathOfReverse);
                // 更新
                credit.setIdentityPathOfReverse(identityPathOfReverse);
                credit.setUpdateTime(new Date());
                creditService.updateCredit(credit);
                return ajax;
            }
        } else {
            String identityPathOfReverse = FileUploadUtils.upload(RuoYiConfig.getIdentityPathOfReverse(), file);
            //判断是否有一条记录现在只有主键id和identityPathOfReverse两个字段
            Credit creditAlready = creditService.selectNewCreateByUserName(userName);
            String identityPathOfFront = creditAlready.getIdentityPathOfFront();
            String cardIdentity = creditAlready.getCardIdentity();
            if (StringUtils.isNotEmpty(identityPathOfFront) && StringUtils.isNotEmpty(cardIdentity)) {
                creditAlready.setIdentityPathOfReverse(identityPathOfReverse);
                creditService.updateCredit(creditAlready);
                ajax.put("msg", "身份证反面上传成功!");
            } else if (StringUtils.isNotEmpty(identityPathOfFront) && StringUtils.isEmpty(cardIdentity)) {
                creditAlready.setIdentityPathOfReverse(identityPathOfReverse);
                creditService.updateCredit(creditAlready);
                ajax.put("msg", "身份证反面上传成功!");
            }
        }
        return ajax;
    }

}
